//
//  TalkfunSocket.m
//  CloudLive
//
//  Created by LuoLiuyou on 16/8/17.
//  Copyright © 2016年 Talkfun. All rights reserved.
//

#import "TalkfunSocket.h"

#import "SocketUtf8.h"
#import<SystemConfiguration/SystemConfiguration.h>
#import<netdb.h>


@import SocketIO;
@import TalkfunSocketSDK;
static TalkfunSocket *_shared = nil;

@interface TalkfunSocket()
@property (nonatomic,strong)SocketManager* manager;

@property (nonatomic,assign) int timeoutAfter;

@property (nonatomic,copy) NSString *inputEvent;
@property (nonatomic,copy) NSString *broadcastEvent;
@property(nonatomic,assign)int reconnectNumber;
@property(nonatomic,strong)SocketUtf8 *f8;

@property (nonatomic, strong) void(^myBlock)(id obj);

@property(nonatomic,strong)NSTimer *connectTime;

//@property(nonatomic,strong)NSTimer *startLive2;
@end

@implementation TalkfunSocket

- (SocketUtf8 *)f8
{
    if(!_f8){
        _f8 = [[SocketUtf8 alloc]init];
    }
    return _f8;
    
}
- (id)init {
    if(self = [super init]){
        self.timeInterval = 1;
        self.currentIndex = 0;
        self.timeoutAfter = 5;
        self.listener = [[NSMutableDictionary alloc] init];
        
        self.inputEvent = @"income";
        self.broadcastEvent = @"_broadcast";
    
        [self accessToken:self.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:2 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"___init___"];
        
//        self.startLive2 = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(startLive2Click) userInfo:nil repeats:YES];
//        [[NSRunLoop mainRunLoop] addTimer:self.startLive2 forMode:NSDefaultRunLoopMode];
            
    }
    return self;
}

- (void)startLive2Click
{
    
//    NSMutableArray *packet = @[ @{
//        @"cmd": @"chat:send",
//        @"args":@{@"uuid": @"mcfluymi35xl8xbrd",
//                  @"xid": @"1284781513",
//                  @"attr": @{
//                      @"ctagid": @"0",
//                      @"new": @"1",
//                      @"uext": @"",
//                      @"departmentID": @"0"
//                  },
//                  @"uid": @"u_95d26e16ed60d6c0",
//                  @"a": @"0",
//                  @"time": @"1751076707",
//                  @"gid": @"0",
//                  @"avatar": @"https://static-1.talk-fun.com/open/cms_v2/css/common/portraits/user_3.png",
//                  @"msgid": @"07dd7593-726f-4bc2-a196-80f1e2cbdfe9",
//                  @"isMe": @"0",
//                  @"role": @"user",
//                  @"term": @"5",
//                  @"nickname": @"98",
//                  @"msg": @"为什么很多人说小米跑纽北等于跑分？现在是随便一辆车都能上纽北刷分的？",
//                  @"gender": @"0",
//                  @"chat": @{
//                      @"enable": @"1",
//                      @"grant": @"0"
//                  }},
//
//
//    }];
//    NSUInteger packetLength = [packet count];
//    for (NSUInteger i = 0;i < packetLength;i ++){
//        [self onBroadcast:(NSDictionary *)packet[i]];
//    }
    
}

+ (TalkfunSocket *) shared
{
    if ( !_shared )
    {
        _shared = [[TalkfunSocket alloc] init];
    }
    return _shared;
}
- (void)setUser:(NSDictionary *)user {
    if([user objectForKey:@"xid"]){
        self.xid = [[user objectForKey:@"xid"] intValue];
    }
}
- (NSArray *)addresses{
    if(_addresses==nil){
        _addresses = [NSArray array];
    } return _addresses;
}

- (void)connect{
    
    if ( [self.addresses isKindOfClass:[NSArray class]] ) {
        
        if( self.addresses.count > 0 )
        {
          
            if( self.isLiveSDK == true ){
              
                if (self.currentIndex>self.addresses.count) {
                    self.currentIndex = 0;
                }
                if( self.currentIndex<self.addresses.count){
                    [self connectWith:[self.addresses objectAtIndex:self.currentIndex]];
                }
                self.currentIndex ++;
            }else
            {
                    if (self.timeInterval < 64 ) {
                   
                        if (self.currentIndex>self.addresses.count) {
                            self.currentIndex = 0;
                        }
                        //-----------------------
                        if(self.connectTime)
                        {
                            [self.connectTime invalidate];
                            self.connectTime = nil;
                        }
                        //延时重连
                        self.connectTime = [NSTimer timerWithTimeInterval:self.timeInterval target:self selector:@selector(connectTimeClick) userInfo:nil repeats:false];
                        [[NSRunLoop mainRunLoop] addTimer:self.connectTime forMode:NSDefaultRunLoopMode];
                      }else
                      {
                          dispatch_async(dispatch_get_main_queue(), ^{
                                             
                              [[NSNotificationCenter defaultCenter] postNotificationName:@"TalkfunErrorNotification" object:nil userInfo:@{@"code":@(200005),@"msg":@"服务连接失败"}];
                          });
                      }
         
            }
            
        }
   
    }
  
}
- (void)connectTimeClick
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.connectTime)
        {
            [self.connectTime invalidate];
            self.connectTime = nil;
        }
        if ( [self.addresses isKindOfClass:[NSArray class]] ) {
            
            if( self.currentIndex<self.addresses.count ){
                
                [self connectWith:[self.addresses objectAtIndex:self.currentIndex]];
            }
        }
        
        self.currentIndex ++;
        //重连的间距时长 2 4 8 16 32  64
        self.timeInterval = self.timeInterval * 2;
    });
}
//获取手机UUID
- (NSString *)getUUID
{
    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
- (void)connectWith:(NSString *)address {
    if (self.access_token == nil) {
        return;
    }
    ///创建的话要杀死
    if (self.manager) {
        [self disconnect];
    }
    
    if (![address containsString:@"http"]) {
        address = [NSString stringWithFormat:@"https:%@",address];
    }


    //观看直播
    NSDictionary*dict = nil;
    
    //sessionid  设置过数据
    if([self.sessionid isKindOfClass:[NSString class]]){
        
        NSString *sessionid = self.sessionid;
     
        if ([[self getUUID] isKindOfClass:[NSString class]]&&[self getUUID].length>0) {
            sessionid = [self getUUID];
        }
        
     dict = @{@"log": @NO, @"forceWebsockets":@YES,@"connectParams":@{@"access_token":self.access_token,
                                                                 @"sessionid":sessionid,
                                                                      @"xid":[NSString stringWithFormat:@"%ld",self.xid]                                                                                                      },@"compress":@YES,@"extraHeaders":@{@"User-Agent":self.userAgent?self.userAgent:@""}};
    }else{
     
        dict = @{@"log": @NO, @"forceWebsockets": @YES,@"connectParams":@{@"access_token":self.access_token},@"compress":@YES,@"extraHeaders":@{@"User-Agent":self.userAgent?self.userAgent:@""}};
    }

    
    [self socketPrint:@"socketManager初始化" parameter:dict?dict:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
    //TODO:  SocketManager初始化
      self.manager = [[SocketManager alloc] initWithSocketURL:[[NSURL alloc] initWithString:address] config:dict];
    NSString *defaultSocket_sid = [TalkfunSocketSDK get_defaultSocket_sidWithManager:self.manager];

    __weak typeof(self) weakSelf = self;
    [TalkfunSocketSDK onManager:self.manager event:@"connect" callback:^(NSArray * _Nonnull data) {
        
        [weakSelf accessToken:weakSelf.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:2 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:[NSString stringWithFormat: @"socket connect success :%@  sid :%@", address,defaultSocket_sid]];
        

        [weakSelf fire:@"connect" params:[data count] > 0 ? data[0] : nil];
        
        
        [weakSelf socketPrint:@"socketManager_connect" parameter:dict?dict:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
        if (weakSelf.log) {
            
            if ([weakSelf.delegate respondsToSelector:@selector(socket:sid:status:)]) {
                 [weakSelf.delegate socket:address sid:defaultSocket_sid status:@"connect"];
            }
           
        }
    }];
    //TODO:  SocketManager准备重连
    [TalkfunSocketSDK onManager:self.manager event:@"reconnect" callback:^(NSArray * _Nonnull data) {

        
        [weakSelf accessToken:weakSelf.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:3 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"socket reconnect"];
        
        
        [weakSelf socketPrint:@"socketManager重连" parameter:dict?dict:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
        
        [weakSelf fire:@"reconnect" params:[data count] > 0 ? data[0] : nil];
        if (weakSelf.log) {
            
            weakSelf.reconnectNumber = weakSelf.reconnectNumber+1;
            
        
            if ([weakSelf.delegate respondsToSelector:@selector(socket:sid:status:number:)]) {
                
                [weakSelf.delegate socket:address sid:defaultSocket_sid status:@"reconnect" number:weakSelf.reconnectNumber ];
            }
            
        }
    }];
    //TODO: SocketManager真正开始重连
    [TalkfunSocketSDK onManager:self.manager event:@"reconnectAttempt" callback:^(NSArray * _Nonnull data) {
       
        [weakSelf accessToken:weakSelf.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:3 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"socket reconnectAttempt"];
        [weakSelf fire:@"reconnectAttempt" params:[data count] > 0 ? data[0] : nil];
        
        [weakSelf socketPrint:@"socketManager重新连接尝试" parameter:dict?dict:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
        
        if (weakSelf.log) {
            
           
            
            if ([weakSelf.delegate respondsToSelector:@selector(socket:sid:status:)]) {
                 [weakSelf.delegate socket:address sid:defaultSocket_sid status:@"reconnectAttempt"];
            }
        }
    }];
    //TODO:  SocketManager错误
    [TalkfunSocketSDK onManager:self.manager event:@"error" callback:^(NSArray * _Nonnull data) {
       
        
        [weakSelf accessToken:weakSelf.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:4 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"socket error"];
        
        NSMutableDictionary *v1 = [NSMutableDictionary dictionary];
        [v1 setObject:address?address:@"" forKey:@"initWithSocketURL"];
        [v1 setObject:dict?dict:@{} forKey:@"SocketConfig"];
        [v1 setObject:data?data:@"" forKey:@"error"];
//        NSLog(@"socketManager错误信息>%@",v1);
        [weakSelf fire:@"error" params:[data count] > 0 ? data[0] : nil];
        
        [weakSelf socketPrint:@"socketManager错误信息" parameter:v1?v1:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
        
        if (weakSelf.log) {
            
            if ([weakSelf.delegate respondsToSelector:@selector(socket:sid:status:)]) {
                [weakSelf.delegate socket:address sid:defaultSocket_sid status:@"error"];
            }
           
           
        }
                //先杀死
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf disconnect];
        
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                        // 这里写需要延时执行的代码
//                        NSLog(@"延时2秒后执行重连");
                        //重新连接
                      [weakSelf connect];
                    });
              });
      
    }];
    //TODO: 连接断开 事件
    [TalkfunSocketSDK onManager:self.manager event:@"disconnect" callback:^(NSArray * _Nonnull data) {

        [weakSelf accessToken:weakSelf.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:3 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"socket disconnect"];
        [weakSelf fire:@"disconnect" params:[data count] > 0 ? data[0] : nil];
        
        [weakSelf socketPrint:@"socketManager连接断开" parameter:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
        
        if (weakSelf.log) {
            
            if ([weakSelf.delegate respondsToSelector:@selector(socket:sid:status:)]) {
                 [weakSelf.delegate socket:address sid:defaultSocket_sid status:@"disconnect"];
            }
          
           
        }
    }];
    //TODO:  进入房间成功 事件
    [TalkfunSocketSDK onManager:self.manager event:@"member:join:me" callback:^(NSArray * _Nonnull data) {
        
//        NSLog(@"进入房间成功");
        [weakSelf socketPrint:@"socketManager进入房间成功" parameter:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
        //重连时间间隔
        weakSelf.timeInterval = 1;
        weakSelf.currentIndex = 0;
        
        if (_myBlock) {
            //TALKFUN_CLOUDLIVE_EVENT_MEMBER_LIST
            [weakSelf emit:@"member:list" args:@{@"page":@(1),@"size":@(100)} callback:_myBlock];
        }
    
          [weakSelf accessToken:weakSelf.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:1 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"socket member:join:me"];
        if(!weakSelf.user){
            if([data count] > 0){
                NSDictionary *member = [data[0] objectForKey:@"member"];
                weakSelf.user = member;
            }
        }
        
        NSDictionary *params = [data count] > 0 ? data[0] : nil;

        //json 转字典
        NSDictionary  *paramsDatd = [weakSelf getPacketDict:params];
        
        [weakSelf fire:@"member:join:me" params:paramsDatd];
    }];

    //TODO:  SocketManager事件
    [TalkfunSocketSDK onManager:self.manager event:self.broadcastEvent callback:^(NSArray * _Nonnull data) {
        if([data count] > 0){
            id packet = data[0];
//            NSLog(@"SocketManager接收的源数据===>==>%@",data);
//            TalkfunLogger_Debug(weakSelf.access_token?weakSelf.access_token:@"",@"socket onBroadcast : %@",packet);
            
            if([packet isKindOfClass:[NSArray class]]){
                NSUInteger packetLength = [packet count];
                for (NSUInteger i = 0;i < packetLength;i ++){
                    [weakSelf onBroadcast:(NSDictionary *)packet[i]];
                }
            }else if([packet isKindOfClass:[NSDictionary class]]){
                [weakSelf onBroadcast:(NSDictionary *)packet];
            }else if([packet isKindOfClass:[NSString class]]){
                NSDictionary *response =[NSJSONSerialization JSONObjectWithData:packet options:0 error:nil];
                [weakSelf onBroadcast:response];
            }
        }
    }];
    
//    //所有事件
//    [self.manager.defaultSocket onAny:^(SocketAnyEvent * _Nonnull event) {
//
//        NSLog(@"所有事件===>%@",event);
//
//    }];
    
    [TalkfunSocketSDK connectWithManager:self.manager];
}

- (NSString*)getDecode:(NSString*)msg
{
   return  [self.f8 decode:msg?msg:@""];
}
- (NSDictionary *)getPacketDict:(NSDictionary*)paramsDatd
{
    if ([paramsDatd isKindOfClass:[NSDictionary class]]) {
        //字典转json
        NSString *JsonData  =  [self convertToJsonData:paramsDatd];
        
        //json转码处理乱码问题
        NSString *stringDatd = [self getDecode:JsonData?JsonData:@""];
        
        //json 转字典
        NSDictionary  *packet  =  [self dictionaryWithJsonString:stringDatd ];
        
        if ([packet isKindOfClass:[NSDictionary class]]) {
            return packet;
        }
        
    }
    return @{};
}
- (void)onBroadcast:(NSDictionary *)packet3 {
    if(![packet3 isKindOfClass:[NSDictionary class]]){
        return;
    }
    NSDictionary *packet = [self getPacketDict:packet3];
    if(!self.xid){
        return;
    }
   
    
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"award:send"]) {
       
        if ( [packet[@"args"] isKindOfClass:[NSDictionary class]]) {
             [self agoraKit:[packet objectForKey:@"cmd"] params: packet[@"args"]];
              return;
        }
        
    }
    //拒绝连麦 跟邀请
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:respondinvite"]) {
         
          if ( [packet[@"args"] isKindOfClass:[NSDictionary class]]) {
             
           NSString *inviteStatus =  packet[@"args"][@"inviteStatus"];
              if ([inviteStatus isKindOfClass:[NSString class]]) {
                      //同意
                   if ([inviteStatus isEqualToString:@"accept"]) {
                       [self fire:@"rtc:accept" params:packet[@"args"]];
                       
                   } else if ([inviteStatus isEqualToString:@"reject"]){
                       //拒绝
                       [self fire:@"rtc:reject" params:packet[@"args"]];
                   }
                 return;
              }
           
              
               
          }
          
      }
    
    //rtc 全体互动
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:globalstatus"]) {
          
        if ([self.delegate respondsToSelector:@selector(rtcGlobalstatus:)]) {
            [self.delegate rtcGlobalstatus:packet];
        }
    }
    //取消邀请上讲台
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:invitecancel"]) {
    
         [self agoraKit:[packet objectForKey:@"cmd"] params: packet];
      
          return;
    }
    
   //抽奖开始
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"lottery:start"]) {
          
        if ([self.delegate respondsToSelector:@selector(socketLotteryStart:)]) {
            if ([packet[@"args"] isKindOfClass:[NSDictionary class]]) {
                [self.delegate socketLotteryStart:packet[@"args"]];
            }else{
                [self.delegate socketLotteryStart:@{}];
            }
           
        }
    }
    //抽奖结束
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"lottery:stop"]) {
     
        if ([self.delegate respondsToSelector:@selector(socketLotteryStop:pub:gid:currentXid:)]) {
            if (packet[@"args"]) {
                
            if (packet[@"args"][@"result"]&&packet[@"args"][@"gid"]&&packet[@"args"][@"pub"]) {
                    
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
                dispatch_async(queue, ^{
                                               
                                               
                           NSMutableArray *copyArray = [NSMutableArray array];
                           for (NSDictionary *dict in packet[@"args"][@"result"]) {
                               if ([dict isKindOfClass:[NSDictionary class]]) {
                                    NSMutableDictionary *copyDicgt = [NSMutableDictionary dictionaryWithDictionary:dict];
                                   [copyDicgt setObject: [self getNumber_0:dict[@"xid"]] forKey:@"xid"];
                                  
                                   [copyArray addObject:copyDicgt];
                               }
                              
                               
                           }

                     dispatch_async(dispatch_get_main_queue(), ^{
                         [self.delegate socketLotteryStop:copyArray pub:packet[@"pub"] gid:packet[@"gid"] currentXid:[NSString stringWithFormat:@"%li",(long)self.xid ]];
                     });

                    });
               

                }
               
            }
            
            
        }
        
        if ([self.delegate respondsToSelector:@selector(socketLotteryStopforAll:)]){
           
            if (packet[@"args"] && [packet[@"args"] isKindOfClass:[NSDictionary class]]) {
//                NSLog(@"抽奖结束socket===%@",packet);
                [self.delegate socketLotteryStopforAll:packet[@"args"]];
            }
            
        }
       
    }
  
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:invite"]) {
        
        NSString * xid =  [self getNumber_0:packet[@"args"][@"xid"]];
      
        if([packet[@"args"] isKindOfClass:[NSDictionary class]]){
                if ([packet[@"args"][@"inviteStatus"]isKindOfClass:[NSString class]]){
                    
           NSString *inviteStatus  = packet[@"args"][@"inviteStatus"];
//                    NSLog(@"xid ==%ld",self.xid);
                if ([xid integerValue]==self.xid) {
                    
                    [self agoraKit:[packet objectForKey:@"cmd"] params:@{@"inviteStatus":inviteStatus?inviteStatus:@""}];
                   
                }
                 return;
            }
        }
     
    }
    //投票的不用转码,因为开始时间会乱 投票结束也一样
    if ([[packet objectForKey:@"cmd"] isEqualToString:@"vote:new"]||[[packet objectForKey:@"cmd"] isEqualToString:@"vote:pub"]){
        
        if ([packet[@"args"] isKindOfClass:[NSDictionary class]]) {
            NSMutableDictionary *argsDict = [NSMutableDictionary dictionaryWithDictionary:packet[@"args"]];
            
            if (argsDict[@"info"]) {
            NSMutableDictionary *infoDict = [NSMutableDictionary dictionaryWithDictionary:argsDict[@"info"]];
                
                
                [infoDict setObject:[self getDecode:infoDict[@"title"]] forKey:@"title"];
                
                
                [argsDict setObject:infoDict forKey:@"info"];
                
            }
            [self fire:[packet objectForKey:@"cmd"] params:argsDict];
            return;
        }
     
    }
    NSString *defaultSocket_sid = [TalkfunSocketSDK get_defaultSocket_sidWithManager:self.manager];
    if([packet objectForKey:@"nosid"]){
        NSArray *nosid = [packet objectForKey:@"nosid"];
        if([nosid count] > 0){
            if([nosid containsObject:defaultSocket_sid]){
                return;
            }
        }
    }
    
    if([packet objectForKey:@"noxid"]){
        NSArray *noxid = [packet objectForKey:@"noxid"];
        if([noxid count] > 0){
            NSString * xid = [NSString stringWithFormat:@"%ld",(long)self.xid];
            NSNumber * xidn = @(self.xid);
            if([noxid containsObject:xid] || [noxid containsObject:xidn]){
                return;
            }
        }
    }

    if ([[packet objectForKey:@"cmd"] isKindOfClass:[NSString class]]) {

        //开启讲台模式
        if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:start"]){
            [self agoraKit:@"rtc:start" params:packet];
            return;
        }
        //关闭讲台模式
        else if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:stop"]){

            [self agoraKit:@"rtc:stop" params:packet];
              return;
        }
        //允许上讲台 TALKFUN_EVENT_RTC_USER_UP
        else if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:up"]){
            [self agoraKit:@"rtc:up" params:packet];
        return;
        }
        ////踢下讲台
        else if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:kick"]){
        [self agoraKit:@"rtc:kick" params:packet];

          return;
        }

  //主动下讲台
    else if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:down"]){
        
        [self agoraKit:@"rtc:down" params:packet];
        
        return;
     //拒绝用户上讲台
    } else if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:rejectapply"]){
           
           [self agoraKit:@"rtc:rejectapply" params:packet];
           
           return;
       }
        //job:1.打开报像头,2.关闭摄像头,3.打开麦克风,4.关闭麦克风
        else if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:media"]){

                if (packet[@"args"][@"job"]) {
                    if ( [ packet[@"args"][@"job"] intValue]==1) {
                        //打开报像头
                        [self agoraKit:@"camera:on" params:packet];
                          return;
                    }
                    else  if ( [ packet[@"args"][@"job"] intValue]==2) {
                        //关闭摄像头

                        [self agoraKit:@"camera:off" params:packet];
                          return;
                    }else  if ( [ packet[@"args"][@"job"] intValue]==3) {
                        //打开麦克风

                        [self agoraKit: @"microphone:on" params:packet];
                          return;
                    }

                    else  if ( [ packet[@"args"][@"job"] intValue]==4) {
                        //关闭麦克风

                        [self agoraKit: @"microphone:off" params:packet];
                          return;
                    }
                }



        }

        //job:1.获取画线权限，2.被禁用画线权限
        else if ([[packet objectForKey:@"cmd"] isEqualToString:@"rtc:power"]){

                if (packet[@"args"][@"job"]) {
                    if ( [ packet[@"args"][@"job"] intValue]==1) {
                        //打开画线权限
                        [self agoraKit: @"whiteboard:on" params:packet];
                           return;
                    }
                   else   if ( [ packet[@"args"][@"job"] intValue]==2) {
                        //关闭画线权限
                        [self agoraKit:@"whiteboard:off" params:packet];
                         return;

            }

        }
        }
    }
    //机器人 主播更新了机器人列表
    if([packet isKindOfClass:[NSDictionary class] ]&& [packet[@"cmd"] isEqualToString:@"member:robots"]){
        
        if (packet[@"args"][@"robots"][@"total"]) {
            //机器人总数
            self.robotCount = [packet[@"args"][@"robots"][@"total"] integerValue];

            [self addRobotList:packet];
       
           return;

        }
        
    }
    
    NSString *cmd = [packet objectForKey:@"cmd"];
    //这里不是小班的监听
    id args = [packet objectForKey:@"args"];
    if ([cmd isKindOfClass:[NSString class]] ) {
        
        if ( [cmd hasPrefix:@"third:"]  && [args isKindOfClass:[NSDictionary class]]) {
            
            NSMutableDictionary *args = [NSMutableDictionary dictionaryWithDictionary:packet[@"args"]];
            //第三方自定义通知
            [self fire:@"broadcast:third" params:@{@"cmd":cmd,@"args":args}];
            return;
            
        }
    }

    
    if ([args isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:[packet objectForKey:@"args"]];
        if (params[@"member"]) {
            params = [NSMutableDictionary dictionaryWithDictionary:[packet objectForKey:@"args"][@"member"]];
        }
        if (params[@"a"]&&[params[@"a"] intValue]==1) {
            
            NSString *xid_ = [self getNumber_0:params[@"xid"]];
        
            NSString * avatar = [self getAvatarString:xid_ avatarHost:self.avatarHost];
            
            if ([params[@"attr"] isKindOfClass:[NSDictionary class]]) {
            if (params[@"attr"][@"v"]) {
                avatar = [avatar stringByAppendingString:@"?v="];
                avatar = [avatar stringByAppendingString:[self getNumber_0:params[@"attr"][@"v"]]];
                }
            }
            
            if(avatar){
                params[@"avatar"] = avatar;
            }
            [params removeObjectForKey:@"a"];
        }else if (params[@"a"]&&[params[@"a"] intValue]==0) {
           
            
            NSString*avatar = params[@"avatar"];
            if([avatar isKindOfClass:[NSString class]]&&avatar.length>0)
            {
                
            }else
            {
                //默认头像
                NSString *role = params[@"role"];
                if (role) {
                    if ([role isKindOfClass: [NSString class]]) {
                        //默认头像
                        if ( self.defaultAvatar[role]) {
                            [params setObject: self.defaultAvatar[role] forKey:@"avatar"];
                        }
                        
                        
                    }
                    
                }
            }
           
            
        }
        //互动工具的抢答器专用
        if ([packet[@"data"] isKindOfClass:[NSDictionary class]]) {
            if ([packet[@"data"][@"cmd"] isKindOfClass:[NSString class]]) {
                if ([packet[@"data"][@"cmd"] isEqualToString:@"interaction"]) {
                    [self fire:packet[@"data"][@"cmd"] params:@{@"interaction":packet[@"data"]}];
                    return;
                }
            }
        }
        
        @synchronized(self){
            
            if(![params isKindOfClass:[NSDictionary class] ]){
                return;
            }
      
            //json 转字典
            NSDictionary  *paramsDatd = [self getPacketDict:params];
            
            
            if([paramsDatd isKindOfClass:[NSDictionary class]]){
                
                //聊天数据乱码
                if ([[packet objectForKey:@"cmd"] isEqualToString:@"chat:send"]&&paramsDatd) {
                    
                    NSMutableDictionary *copyDict = [NSMutableDictionary dictionaryWithDictionary:paramsDatd];
                    //是自己
                    if ([[self getNumber_0:copyDict[@"xid"]]  integerValue] == self.xid) {
                        [copyDict setObject:@"1" forKey:@"isMe"];
                    }else{
                        [copyDict setObject:@"0" forKey:@"isMe"];
                    }
                    //聊天内容
                    if (paramsDatd [@"msg"]) {
                        NSString * msg =  paramsDatd [@"msg"];
                        
                        msg =  [self getDecode:msg?msg:@""];
                        [copyDict setObject:msg forKey:@"msg"];
                        [self fire:[packet objectForKey:@"cmd"] params:copyDict?copyDict:@{}];
                    }
                   
                }else{
                    
                    if(packet[@"args"]){
                        
                        if (packet[@"args"][@"member"]) {
                            
                            NSMutableDictionary * copyPacket =[NSMutableDictionary dictionaryWithDictionary:packet];
                            
                            if (packet[@"args"][@"total"]) {
                                
                                [copyPacket setObject:packet[@"args"][@"total"] forKey:@"total"];
                            }
                            
                            
                            NSMutableDictionary *member = [NSMutableDictionary dictionary];
                            
                            [member setObject:paramsDatd?paramsDatd:@{} forKey:@"member"];
                            
                            [copyPacket setObject:member forKey:@"args"];
                            
                            [self fire:[packet objectForKey:@"cmd"] params:copyPacket?copyPacket:@{}];
                            return;
                            
                        }
                        //公告 与提问
                        else if ([[packet objectForKey:@"cmd"] isEqualToString:@"announce:notice"]||[[packet objectForKey:@"cmd"] isEqualToString:@"question:ask"])
                        {
                            NSMutableDictionary *copyPacket = [NSMutableDictionary dictionaryWithDictionary:packet];
                                             
                           
                            
                            if (copyPacket[@"args"]) {
                            NSMutableDictionary *copyArgs = [NSMutableDictionary dictionaryWithDictionary:copyPacket[@"args"]];
                                
                            NSString *content =   [self getDecode:copyArgs[@"content"]];
                                
                            [copyArgs setObject:content forKey:@"content"];
                              
                            [self fire:[packet objectForKey:@"cmd"] params:copyArgs];
                                return;
                            }
                            
                        }
                    }
                    
                    NSMutableDictionary *copyParamsDatd = [NSMutableDictionary dictionaryWithDictionary:paramsDatd?paramsDatd:@{}];
                    
                    //个体禁言
                    if ([[packet objectForKey:@"cmd"] isEqualToString: @"chat:disable"]||[[packet objectForKey:@"cmd"] isEqualToString:@"chat:enable"]){
                        NSString *isMe = @"0";
                        if ([copyParamsDatd[@"xid"] integerValue] == self.xid) {
                                  isMe = @"1";
                        }
                        
                        [copyParamsDatd setObject:isMe forKey:@"isMe"];
                      
                      }
                    [self fire:[packet objectForKey:@"cmd"] params:copyParamsDatd];
                }
                
                
                
            }
            if (self.lecturer) {
                
                //画板的初始化
                if ([packet[@"cmd"] isEqualToString:@"video:whiteboard"]) {
                    
                     [self fire:packet[@"cmd"] params:packet];
                    
                }
                
            }
            
        }
        
    }
    else if ([packet isKindOfClass:[NSArray class]]){
        [self fire:packet[@"cmd"] params:packet[@"args"]];
    }
    else if ([[packet objectForKey:@"cmd"] isEqualToString:@"member:total"]){

        [self fire:[packet objectForKey:@"cmd"] params:@{@"total":args?args:@""}];
    }
    else {
        if ([packet isKindOfClass:[NSDictionary class]]&&[packet objectForKey:@"cmd"]) {
             [self fire:[packet objectForKey:@"cmd"] params:args];
        }
        
    }
   
    
}
- (void)addRobotList:(NSDictionary *)packet
{
    
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
        

        NSArray *list = packet[@"args"][@"robots"][@"list"];
        NSMutableArray *memberList1 = [NSMutableArray array];
        NSMutableArray *memberList2 = [NSMutableArray array];

        for (NSDictionary *robotDict in list) {
            if ([robotDict isKindOfClass:[NSDictionary class]]) {

            NSMutableDictionary *robotDict1 = [NSMutableDictionary dictionaryWithDictionary:robotDict];

            if (robotDict1[@"a"] ==nil &&robotDict1[@"avatar"]==nil) {
            [robotDict1 setObject:@"0" forKey:@"a"];
            }
            if (robotDict1[@"role"] ==nil ) {
            [robotDict1 setObject:@"user" forKey:@"role"];
            }

            [memberList1 addObject:robotDict1];
            }
        }

        for (NSDictionary *robotDict1 in memberList1)
        {

           [memberList2 addObject:robotDict1];

        }
     
        dispatch_async(dispatch_get_main_queue(), ^{
           
    
                //机器人列表
            self.memberList = memberList2;
            
        
            if ([self.delegate respondsToSelector:@selector(updatememberTotal:callback:)]) {
                
                void (^callback)(id result) = [self.listener objectForKey:@"member:total"];
                 [self.delegate updatememberTotal:packet[@"args"] callback:callback];
                
             }

            
            
        });
        
    });
}

- (void)disconnect {
    if(self.manager){
        [TalkfunSocketSDK disconnectWithManager:self.manager broadcastEvent:self.broadcastEvent];
        
//        [self.manager.defaultSocket off:@"connect"];
//        [self.manager.defaultSocket off:@"reconnect"];
//        [self.manager.defaultSocket off:@"error"];
//        [self.manager.defaultSocket off:@"reconnectAttempt"];
//        [self.manager.defaultSocket off:@"disconnect"];
//        [self.manager.defaultSocket off:@"member:join:me"];
//        [self.manager.defaultSocket off:self.broadcastEvent];
//
//        [self.manager.defaultSocket disconnect];
//        [self.manager disconnect];
        self.manager = nil;

    }
}

- (void)shutdown
{
    if(self.connectTime)
    {
        [self.connectTime invalidate];
        self.connectTime = nil;
    }
    self.timeInterval = 1;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    // 主动释放 SocketUtf8 的队列资源
    if (self.f8) {
        [self.f8 releaseQueue];
        self.f8 = nil;
    }
    
    [self disconnect];
    _shared = nil;
//    [self socketPrint:@"socket调用销毁" parameter:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
    [self deallocUI];
}

#pragma mark    emit without callback
- (void)emit:(NSString *)event args:(NSMutableDictionary *)args {
    [self emit:event args:args callback:nil];
}

#pragma mark    emit with callback
- (void)emit:(NSString *)event args:(NSMutableDictionary *)args callback:(void (^)(id))callback {
    

   // 如果是http接口的调用，使用httpEmiter进行调用
    if ([self.delegate respondsToSelector:@selector(handle:)]) {
        
        if([self.delegate handle:event]){
            
    if ([self.delegate respondsToSelector:@selector(emit:params:callback:)]) {
             __weak typeof(self) weakSelf = self;
        [self.delegate emit:event params:args callback:^(NSDictionary *dict1) {
            if ([dict1 isKindOfClass:[NSDictionary class]]) {
                NSMutableDictionary *copy1 = [NSMutableDictionary dictionaryWithDictionary:dict1];
                
                if ([copy1[@"info"] isKindOfClass:[NSDictionary class]]) {
                    NSMutableDictionary *infoDict =  [NSMutableDictionary dictionaryWithDictionary:copy1[@"info"]];
                    
                    [infoDict setObject:[weakSelf getDecode:infoDict[@"title"]] forKey:@"title"];
                    
                    [copy1 setObject:infoDict forKey:@"info"];
                }
                if (callback) {
                    callback(copy1);
                }
                 
            }else{
                if (callback) {
                    callback(dict1);
                }
                
            }
            
        }];
        return;
        
        }
        
        }
    }
    //是获取在线列表
    if (event&&[event isEqualToString:@"member:list"]&&[TalkfunSocketSDK get_defaultSocketWithManager:self.manager] == nil) {
        self.myBlock = callback;
        
    }
   
   else if([TalkfunSocketSDK get_defaultSocketWithManager:self.manager]&&event){
        NSArray *packet = @[@{
                                 @"cmd":event,
                                 @"args":@[args]
                                 }];
        
        __weak typeof(self) weakSelf = self;
       
       
       
        if(callback){
//            NSLog(@"evevevevev:%@  packet:%@",event,packet);
            //[self.socket emit:self.inputEvent with:packet]
            //禁言  解开禁言    踢出房间
//            TALKFUN_EVENT_CHAT_DISABLE @"chat:disable"
            //TALKFUN_EVENT_CHAT_ENABLE "chat:enable"
            //TALKFUN_EVENT_MEMBER_KICK @"member:kick"
        if ([event isEqualToString: @"chat:disable"]||[event isEqualToString:@"chat:enable"]||[event isEqualToString:@"member:kick"]) {
            if (args[@"xid"]) {
                packet = @[@{
                               @"cmd":event,
                               @"args":@[args[@"xid"]]
                               }];
            }
           
  
  

        }else if ([event isEqualToString:@"chat:disable:all"]) {
           
          NSNumber * status = args[@"status"]?args[@"status"]:@(0);
          packet = @[@{
                                @"cmd":event,
                                @"args":@[status]}];
           
        }
//            NSLog(@"packet:%@",packet);
            
            [TalkfunSocketSDK onManager:self.manager emitWithAck:self.inputEvent withArray:packet timeoutAfter:self.timeoutAfter callback:^(NSArray * _Nonnull data) {
//                TalkfunCodeUnknownError = 1000
                if(![data isKindOfClass:[NSArray class]] || [data.firstObject isKindOfClass:[NSString class]]){
                    if([weakSelf connectedToNetwork]){

                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                            [weakSelf emit:event args:args callback:callback];
                            
                           });
                       
                    }else{
                        if (callback) {
                            callback(@{@"code":@(200001),@"msg":@"网络连接已断开"});
                        }
                         
                    }
                    if (_myBlock) {
                        _myBlock = nil;
                    }
                   
                    return;
                }

                
                [weakSelf accessToken:weakSelf.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:2 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"socket emit : %@ ,response"];
                if([data count] > 0){
                    id response = data[0];
                    
                    if([response isKindOfClass:[NSDictionary class]] && [response objectForKey:@"code"]){
                        if([[response objectForKey:@"code"] integerValue] == -5){
                            
                        }else{
                            
                            
                            
                            //只修改发出去的聊天
                            if ([response isKindOfClass:[NSDictionary class]]) {
                                 NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithDictionary:response];
                                
                               if (response[@"data"][@"a"]&&[response[@"data"][@"a"] intValue]==1) {
                                   
                                   NSObject*xid = nil;
                                   if (response[@"data"][@"xid"]) {
                                       xid = response[@"data"][@"xid"];
                                   }
                                  else if (response[@"xid"]) {
                                       xid = response[@"xid"];
                                  }
                                   
                                   
                                    NSString * avatar = [weakSelf getAvatarString:[NSString stringWithFormat:@"%@",xid] avatarHost:weakSelf.avatarHost];
                                    
                                      NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithDictionary:dict1[@"data"]];
                                    
                                    //设置默认头像
                                    [dict2 setObject:avatar?avatar:@"" forKey:@"avatar"];
                                    
                                    //头像
                                    [dict1 setObject:dict2 forKey:@"data"];
                                    
       
                                }else if (response[@"data"][@"a"]&&[response[@"data"][@"a"] intValue]==0) {
                                   
                                    
                                    if (response[@"data"]) {
                                        if (response[@"data"][@"chat"]) {
                                            
                                            if ( dict1[@"data"][@"role"]) {
                                                
                                                if (weakSelf.defaultAvatar[dict1[@"data"][@"role"]]) {
                                                    
                                                    
                                                    NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithDictionary:dict1[@"data"]];
                                                    
                                                    
                                                    //设置默认头像
                                                    [dict2 setObject:weakSelf.defaultAvatar[dict1[@"data"][@"role"]] forKey:@"avatar"];
                                                    
                                                    //头像
                                                    [dict1 setObject:dict2 forKey:@"data"];
                                                    
                                                    
                                                }
                                                
                                            }
                                            
                                        }
                                    }
                                }
                                
                                //字典类型
                                if ([dict1[@"data"] isKindOfClass:[NSDictionary class]]) {
                                    NSString *xid = [weakSelf getNumber_0:dict1[@"data"][@"xid"]];
                                    if ([xid integerValue] ==weakSelf.xid) {
                                        //是自己
                                       NSMutableDictionary *data =  [NSMutableDictionary dictionaryWithDictionary:dict1[@"data"]];
                                        [data setObject:@"1" forKey:@"isMe"];
                                        
                                        [dict1 setObject:data forKey:@"data"];
                                    }else{
                                        //不是自己
                                        NSMutableDictionary *data =  [NSMutableDictionary dictionaryWithDictionary:dict1[@"data"]];
                                        [data setObject:@"0" forKey:@"isMe"];
                                        
                                        [dict1 setObject:data forKey:@"data"];
                                    }
                                }
                                
                                
                                
                                
                                
                                //聊天内容
                                if ([dict1[@"data"] isKindOfClass:[NSDictionary class]]){
                                    
                                  NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:dict1[@"data"]];
                                    
                                    NSString * msg =    data[@"msg"];
                                   

                                      
                                    [data setObject:msg?msg:@"" forKey:@"msg"];
                                    
                                    [data setObject:[self getDecode:data[@"nickname"]] forKey:@"nickname"];
                                        [dict1 setObject:data forKey:@"data"];
                                    
                                     
                                }
                                
                                
                                if (callback) {
                                    callback(dict1);
                                }
                                
                                
                            }else{
                                if (callback) {
                                    callback(response);
                                }
                                 
                            }
                           
                            
                           
                        }
                    }else{
                        //调用了 - (void)getMemberList:(TFMemberParams *)params  callback 返回的
                        if (event && [event isEqualToString:@"member:list"] && [response isKindOfClass:[NSArray class]]) {
                            

                            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
                                                       dispatch_async(queue, ^{
                                                           
                                                           NSMutableArray *copyList = [NSMutableArray array];
                                                        //在线人列表  ,直播器专用 TALKFUN_CLOUDLIVE_EVENT_MEMBER_LIST
                                                     
                                                             NSMutableArray *list = [NSMutableArray arrayWithArray:response];
                                                     
                                                         if (weakSelf.isLiveSDK)
                                                         {
                                                             //有机器人列表数据
                                                                 if ([weakSelf.memberList isKindOfClass:[NSArray class]]) {
                                                                      [list addObjectsFromArray:weakSelf.memberList];
                                                                 }
                                                         }
                                                             
                                                            
                                                             
                                                            for (NSDictionary * user in list) {
                                                                
                                                            NSMutableDictionary*params = [NSMutableDictionary dictionaryWithDictionary:user];
                                                                
                                                                if (params[@"a"]&&[params[@"a"] intValue]==1) {
                                                                    NSString * avatar = [weakSelf getAvatarString:[NSString stringWithFormat:@"%@",params[@"xid"]] avatarHost:weakSelf.avatarHost];
                                                                    if(avatar){
                                                                        params[@"avatar"] = avatar;
                                                                    }
                                                                    
                                                                    [copyList addObject:params];
                                                                    
                                                                }else if (params[@"a"]&&[params[@"a"] intValue]==0) {
                                                                    //默认头像
                                                                    NSString *role = params[@"role"];
                                                                    
                                                                    if (role) {
                                                                        if ([role isKindOfClass: [NSString class]]) {
                                                                            //默认头像
                                                                            if ( weakSelf.defaultAvatar[role]) {
                                                                                [params setObject: weakSelf.defaultAvatar[role] forKey:@"avatar"];
                                                                                [copyList addObject:params];
                                                                            }
                                                                            
                                                                            
                                                                        }
                                                                        
                                                                    }
                                                                    
                                                                }else{
                                                                    if (params[@"avatar"]) {
                                                                        [copyList addObject:params];
                                                                    }
                                                                    
                                                                }
                                                                
                                                                if(params[@"nickname"]){
                                                                    //json转码处理乱码问题
                                                                    
                                                                    NSString *stringDatd = [weakSelf getDecode:params[@"nickname"]];
                                                                    
                                                                    
                                                                [params setObject:stringDatd?stringDatd:@"" forKey:@"nickname"];
                                                                }
                                                            
                                                            
                                                            }
                                                        
                                                       dispatch_async(dispatch_get_main_queue(), ^{
                                     
                                                             if(callback){
                                                                 callback(copyList);
                                                             }
                                                                      
                                                               });

                                                       });
                            
                                

                            
                        }else{
                            if(callback){
                                callback(response);
                            }
                        }
                        
                        
                        
                    }
                }
                

            }];
  
            
        }else{
            [TalkfunSocketSDK emitWithManager:self.manager emitWithAck:self.inputEvent withArray:packet];
//            [self.manager.defaultSocket emit:self.inputEvent with:packet];
        }
    }
}

- (NSMutableDictionary*)visitorInfo
{
    if (_visitorInfo ==nil) {
        _visitorInfo = [NSMutableDictionary dictionary];
    }return _visitorInfo;
}
//#pragma mark   声网专用的 执行监听
- (void)agoraKit:(NSString *)event params:(id)response {

    //小班的整件执行回调
    dispatch_async(dispatch_get_main_queue(), ^{

        if([self.listener objectForKey:event]){

             void (^callback)(id result) = [self.listener objectForKey:event];
            if(callback){
                callback(response);
            }

        }else{
       

            if ([self.delegate respondsToSelector:@selector(rtcOn:callback:result:)])
            {
                [self.delegate rtcOn:event callback:nil result:response?response:@{}];
            }

        }
    });

}
#pragma mark    执行监听
- (void)fire:(NSString *)event params:(id)response
{
    dispatch_async(dispatch_get_main_queue(), ^{
                         

        if(event&&[self.listener objectForKey:event]){

        void (^callback)(id result) = [self.listener objectForKey:event];
        if(callback){
            callback(response);
        }

         
            //直播时长 live:duration
            //网络速度 network:speed
            //ijk播放时长 network:speed
        }else if ([self.listener objectForKey:event] == nil)
        {
            
            if ([self.delegate respondsToSelector:@selector(delegateCallback:withParameter:)])
            {
                [self.delegate delegateCallback:event withParameter:response ];
            }
            
        }

    });
}


#pragma mark    注册监听
- (void)on:(NSString *)event callback:(void (^)(id))callback {
    if(event == nil||callback == nil){
        return;
    }
    
    if([self.listener objectForKey:event]){
        [self.listener removeObjectForKey:event];
    }
    
    [self.listener setObject:callback forKey:event];
}

#pragma mark    取消监听
- (void)off:(NSString *)event {
    if([self.listener objectForKey:event]){
        [self.listener removeObjectForKey:event];
    }
}




//字典转jos
-(NSString *)convertToJsonData:(NSDictionary *)dict{

    return [SocketUtf8 dictionarySerializer:dict];
    
}


//os转j字典转jos
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    if (![jsonString isKindOfClass:[NSString class]]) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
//        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
//获取头像urlString
- (NSString *)getAvatarString:(NSString *)xid avatarHost:(NSString *)avatarHost{

    NSInteger xidInt = [xid integerValue];
    return [NSString stringWithFormat:@"%@/avatar/%ld/%ld/%ld/%@.jpg",avatarHost,xidInt%255,xidInt%600,xidInt%1024,xid];
}
- (BOOL)connectedToNetwork{
    
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    
    struct sockaddr_storage zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable&&!needsConnection) ? YES : NO;
}
- (void)deallocUI
{
    
     [self accessToken:self.access_token print: [NSString stringWithFormat:@"%s",__FILE__ ] level:2 func:[NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] line:__LINE__ str:@"___dealloc___"];
    
    [self socketPrint:@"socket_dealloc" parameter:@{} line:[NSString stringWithFormat:@"%i",__LINE__] func: [NSString stringWithFormat: @"%s", __PRETTY_FUNCTION__] className:NSStringFromClass([self class])];
}
- (NSString*)getNumber_0:(NSObject*)obj
{
    NSString *UsersXid = @"0";
    
    if([obj isKindOfClass:[NSNumber class] ]){
        
        NSNumber  *num     = (NSNumber*) obj;
        NSNumberFormatter *tempNum = [[NSNumberFormatter alloc] init];
        
        UsersXid = [tempNum stringFromNumber:num];
    }else if([obj isKindOfClass:[NSString class] ]){
        
        NSString  *str    = (NSString*)obj;
        UsersXid = str;
    }
    
    return UsersXid?UsersXid:@"0";
}

- (void)accessToken:(NSString*)accessToken print: (NSString*) path level: (int) level func: (NSString*) func line: (int) line str: (NSString*) str
{
    dispatch_async(dispatch_get_main_queue(), ^{
     if (accessToken&&path&&func &&str) {
          if ([self.delegate respondsToSelector:@selector(sendAccessToken:print:level:func:line:str:)]) {
                [self.delegate sendAccessToken:accessToken print:path level:level func:func line:line str:str];
                       }
     }
    });

   
}
//行为记录代理
- (void)socketPrint:(NSString*)print
              parameter:(NSDictionary *)parameter
                   line:(NSString*)line
                   func:(NSString*)func
              className:(NSString*)className
{
    dispatch_async(dispatch_get_main_queue(), ^{
     
     if (print&&parameter&&line &&func&&className) {
          if ([self.delegate respondsToSelector:@selector(behaviorManagerPrint:parameter:line:func:className:)]) {
                [self.delegate behaviorManagerPrint:print parameter:parameter line:line func:func className:className];
             }
     }
    });

}

- (NSString*)getAvatarUrl:(NSDictionary*)dict
{
    NSString * avatar = @"";
    if ([dict[@"avatar"]isKindOfClass:[NSString class]]) {
        avatar = dict[@"avatar"];
    }
    if(dict[@"a"] && [dict[@"a"] intValue] == 1){
        avatar = [self getAvatarString:[NSString stringWithFormat:@"%@",dict[@"xid"]] avatarHost:self.avatarHost];
    }else if (dict[@"a"]&&[dict[@"a"] intValue]==0) {
        if (avatar.length>0) {
            
        }else{
            //默认头像
            NSString *role = dict[@"role"];
            if (role) {
                if ([role isKindOfClass: [NSString class]]) {
                    //默认头像
                    if (self.defaultAvatar[role]) {
                        avatar = self.defaultAvatar[role];
                    }
                    
                }
            }
        }
       
    }
    return avatar;
}
- (void)decodeAsync:(NSString*)msg callback:(void(^)(NSString *result))callback{
    [self.f8 decodeAsync:msg?msg:@"" callback:callback];
}

- (void)getPacketDict:(NSDictionary*)paramsDatd callback:(void(^)(NSDictionary *result))callback
{
    if ([paramsDatd isKindOfClass:[NSDictionary class]]) {
        //字典转json
        NSString *JsonData  = [self convertToJsonData:paramsDatd];

        [self decodeAsync:JsonData?JsonData:@"" callback:^(NSString *stringDatd) {
            
            NSDictionary  *packet  =  [self dictionaryWithJsonString:stringDatd ];
            
            if ([packet isKindOfClass:[NSDictionary class]]) {
                if(callback){
                    callback(packet);
                }
            }
        }];
    
    }
   if(callback){
      callback(@{});
      }
}
@end
